package com.example.thymeleaf.controller;

import com.example.thymeleaf.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
public class ThymeleafController {

    @GetMapping("/strings")
    public ModelAndView strings() {
//        视图解析器默认添加.html后缀，再也不用写.html啦
        ModelAndView modelAndView = new ModelAndView("first");

        modelAndView.getModel().put("message", "Hello Thymeleaf");

        modelAndView.addObject("info", "fail");

        modelAndView.addObject("userId", 10);

        List<User> userList = new ArrayList<>();

        userList.add(new User(12, "罗", 20));

        userList.add(new User(28, "燕", 18));

        /**
         *
         * 二者写法等价
         * modelAndView.addObject(userList);
         * */
        modelAndView.addObject("userList", userList);


        return modelAndView;
    }

    @GetMapping("/testThymeleafDateFormat")
    public ModelAndView testThymeleafDateFormat() {
        ModelAndView modelAndView = new ModelAndView("/dateFormat");
        Date date = new Date();
        modelAndView.addObject("today", date);
        return modelAndView;
    }

    @GetMapping("/getMap")
    public ModelAndView getMap(){
        ModelAndView modelAndView = new ModelAndView();

        HashMap<String , User> userMap = new HashMap<>();

        userMap.put("user1",new User(12, "罗", 20));

        userMap.put("user2",new User(28, "燕", 18));

        modelAndView.addObject("userMap",userMap);

        modelAndView.setViewName("/mapTest");

        return modelAndView;
    }

    /**
     * 测试作用域对象
     * @return
     */
    @GetMapping("/testScope")
    public ModelAndView testScope(HttpServletRequest req, HttpServletResponse resp){
        req.setAttribute("reqAttribute","这是HttpServletRequest中的属性");
        req.getSession().setAttribute("sessionAttribute","这是Session中的属性");
        req.getServletContext().setAttribute("applicationAttribute","这是Application中的属性");
        return new ModelAndView("/scope");
    }



}
